<?php
/**
 * @file $HeadURL: tryapply.php $
 * @author $Author: LiangJian (liangjian@haibao.com) $
 * @date $Date: 2015-3-24 下午7:35:32 $
 * @brief 
 */
namespace haibao\cms\data;


class TryApply extends \haibao\cms\data\BaseMysql{

	public function __construct(){
		parent::__construct('\haibao\cms\model\data\TryApply');
	}

	public function getApplyById($tryId){
		return $this->getOneById($tryId);
	}

	public function getApplyByQuery($query){
		return $this->getAll($query);
	}
	
	public function getApplyByUserId($tryId, $userId, $from = 'WEB'){
		//$sql = 'select * from `TryApply` where `TryId`=%s and `UserId`=%s and `From`=%s';
		$sql = 'select * from `TryApply` where `TryId`=%s and `UserId`=%s';
		$result = $this->query($sql, array($tryId, $userId));
		return $result->fetch_assoc();
	}
	
	/**
	 * 用户申请总数和成功数
	 * @param int $userId 用户ID
	 * @return array success:成功数	total:申请总数
	 */
	public function getApplyCount($userId){
		$data = array(
			'total' => 0,
			'success' => 0,
			'unverify' => 0
		);
		// 申请成功数量
		$sql = "select count(*) as count from `TryApply` where UserId=%s and ApplyStatus=%s";
		$result = $this->query($sql, array(
			$userId, \haibao\cms\model\data\TryApply::VERIFY_YES
		));
		while ($result->fetch_assoc()){
			$data['success'] = $result->getData('count');
		}
		
		// 未审核数量
		$sql = "select count(*) as count from `TryApply` where UserId=%s and ApplyStatus=%s";
		$result = $this->query($sql, array(
				$userId, \haibao\cms\model\data\TryApply::VERIFY_NO
		));
		while ($result->fetch_assoc()){
			$data['unverify'] = $result->getData('count');
		}
		
		$data['total'] = $data['success'] + $data['unverify'];
		return $data;
	}
	
	/**
	 * 处理审核结果
	 * @param array $applyIdArr 审核通过的申请记录ID
	 */
	public function verifyApply($applyIdArr, $status = \haibao\cms\model\data\TryApply::VERIFY_YES){
		$inStr = preg_replace('/(\d+)/', '%s', implode(',', $applyIdArr));
		
		$sql = 'update TryApply set ApplyStatus=%s where Id in('.$inStr.') ';
		array_unshift($applyIdArr, $status);
		$this->query($sql, $applyIdArr);
	}
	
	/**
	 * 处理申请记录
	 * @param array $applyIdArr 处理申请记录ID
	 */
	public function dealApply($applyIdArr, $status = \haibao\cms\model\data\TryApply::STATUS_DISABLE){
		$inStr = preg_replace('/(\d+)/', '%s', implode(',', $applyIdArr));
		
		if($status == \haibao\cms\model\data\TryApply::STATUS_DISABLE){
			$sql = 'update TryApply set `Status`=%s, `ApplyStatus`=%s where Id in('.$inStr.')';
			array_unshift($applyIdArr, \haibao\cms\model\data\TryApply::VERIFY_NO);
			array_unshift($applyIdArr, $status);
			$this->query($sql, $applyIdArr);
		}else{
			$sql = 'update TryApply set `Status`=%s where Id in('.$inStr.')';
			array_unshift($applyIdArr, $status);
			$this->query($sql, $applyIdArr);
		}
	}

	/**
	 * 获取已经审核通过的数量
	 */
	public function getSuccessCount($tryId){
		$sql = "select count(*) as count from TryApply where TryId=%s and ApplyStatus=%s";
		$result = $this->query($sql, array(
				$tryId,
				\haibao\cms\model\data\TryApply::VERIFY_YES
		));
		while ($result->fetch_assoc()){
			$count = $result->getData('count');
		}
		return $count;
	}
	
	/**
	 * 添加一条新申请记录
	 */
	public function addTryApply($model){
		$this->add($model);
	}

	/**
	 * 增加PV数量
	 */
	public function addPv($tryId){
		$this->query("update TryProperty set PV = PV+1 where TryId=%s", array($tryId));
	}
	
	/**
	 * 试用心得
	 */
	public function getTryExperience($tryId,$isDetail,$page){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_DZ3 );

        if($isDetail){
            $limit = $page * 20;
            if($page == 0){
                $sql = 'select b.tid,a.userid,a.addtime,b.author,b.subject,b.message,b.attachment,b.pid from `hb_zj_try_feed_byx` as a left join `hb_forum_post` as b on a.tid=b.tid where a.productid=%s and b.`first`=1 and b.invisible=0 and (`status`=4 or `status`=0) order by a.addtime desc limit 20';
                $result = $this->query($sql, array($tryId));
            }else{
                $sql = 'select b.tid,a.userid,a.addtime,b.author,b.subject,b.message,b.attachment,b.pid from `hb_zj_try_feed_byx` as a left join `hb_forum_post` as b on a.tid=b.tid where a.productid=%s and b.`first`=1 and b.invisible=0 and (`status`=4 or `status`=0) order by a.addtime desc limit %s,20';
                $result = $this->query($sql, array($tryId,$limit));
            }
        }else{
            $sql = 'select b.tid,a.userid,a.addtime,b.author,b.subject,b.message,b.attachment,b.pid from `hb_zj_try_feed_byx` as a left join `hb_forum_post` as b on a.tid=b.tid where a.productid=%s and b.`first`=1 and b.invisible=0 and (`status`=4 or `status`=0) order by a.addtime desc';
            $result = $this->query($sql, array($tryId));
        }

        $data = array();
        while ($row = $result->fetch_assoc()){
            $row['avator'] = $this->getAvator($row['userid']);
            $row['attachment'] = $this->getPostFirstPic($row['tid'], $row['pid']);
            $row['message'] = $this->archiverMessage($row['message']);
            array_push($data, $row);
        }
        return $data;
	}
	
	private function getAvator($userId, $size = '100_100'){
		if(!$userId){
			return false;
		}
		
		list($destWidth, $destHeight) = explode("_", $size);
		if($destWidth <= 70){
			$sizeValue = 'small';
		}elseif($destWidth <= 100){
			$sizeValue = 'middle';
		}else{
			$sizeValue = 'big';
		}
		return "http://bbs.haibao.com/uc_server/avatar.php?uid={$userId}&size={$sizeValue}";
	}
	
	/**
	 * 过滤帖子中discuzcode及htmlcode
	 */
	private function archiverMessage($message) {
		if(strpos($message, '[/password]') !== FALSE) {
			return false;
		}
		$message = strip_tags($message);
		$message = preg_replace(array('/\[attach\][0-9]+\[\/attach\]/isU','/\[img[^\]]*\][^\]]+\[\/img\]/isU','/\[i=s\][^\]]+\[\/i\]/isU'), array('','',''), $message);
		$ret = preg_replace(
				array('/&amp;(#\d{3,5};)/', "/\[hide=?\d*\](.*?)\[\/hide\]/is", "/\[postbg\]\s*([^\[\<\r\n;'\"\?\(\)]+?)\s*\[\/postbg\]/is", "/\[\/?\w+=?.*?\]/"),
				array('&\\1','<b>**** Hidden Message *****</b>',''),
			str_replace(
				array('&', '"', '<', '>', "\t", '   ', '', '  '),
				array('&amp;', '&quot;', '&lt;', '&gt;', '&nbsp; &nbsp; &nbsp; &nbsp; ', '&nbsp; &nbsp;', '&nbsp;&nbsp;'),
			$message));
		$ret = strtr($ret, array('\t'=>'', ' '=>'', '&nbsp;'=>''));
		return str_replace("\r\n", '', ltrim(rtrim($ret)));
	}
	
	/**
	 * 帖子首图
	 */
	private function getPostFirstPic($tid, $pid){
		$attachment = null;
		$sql = "select * from `hb_forum_attachment` where tid=%s and pid=%s";
		$result = $this->query($sql, array($tid, $pid));
		$result = $result->fetch_assoc();
		if($result){
			$ret = $this->query('select `uid`,`filename`,`attachment` from hb_forum_attachment_'.$result['tableid'].' where aid=%s', array(
				$result['aid']
			));
			$aArr = $ret->fetch_assoc();
			$attachment = 'data/attachment/forum/'.$aArr['attachment'];
		}
		return $attachment;
	}
	
	/**
	 * 访问量
	 */
	public function getClickNumByTryIds($tryIds){
		if(!$tryIds){
			return false;
		}
		$tryIdStr = implode(',', $tryIds);
		$str = preg_replace('/(\d+)/', '%s', $tryIdStr);
		$sql = "select TryId,PV from TryProperty where TryId in (%s)";
		$result = $this->query($sql,array($tryIds));
		$data = array();
		while ($result->fetch_assoc()){
			$nums = array('clickNum'=>$this->formatNum($result->getData('PV')));
			$data[$result->getData('TryId')] = $nums;
		}
		return $data;
	}
	
	public function replyLog($logArray){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_DZ3 );
		$sql = "insert into hb_zj_forum_reply (fid,start_time,username,content,log,type) values (%s,%s,%s,%s,%s,%s)";
		$this->query($sql,$logArray);
	}
	
	public function commonMember($contentArr){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_DZ3 );
		$userName=array();
		$result = array();
		$data = array();
		foreach($contentArr as $key => $value){
			$userName[] = $value[0];
		}
		if($userName){
			$sql="select uid,username from hb_common_member where username in ('".join("','",$userName)."') ";
			$result = $this->query($sql);
		}
		$i = 0;
		while($result->fetch_assoc()){
			$data[$i]['uid'] = $result->getData('uid');
			$data[$i]['userName'] = $result->getData('username');
			$i++;
		}
		return $data;
	}
	
	public function editViewNum($model){
		$sql="update TryProperty set PV = %s where TryId = %s ";
		$this->query($sql,array($model->PV,$model->TryId));
	}
	
	public function getApplyArrByUserId($uid, $tryIdArr){
	    $result = array();
	    $sql = "SELECT TryId FROM `TryApply` WHERE UserId =%s AND TryId in (".implode(',', $tryIdArr).")";
	    $data = $this->query($sql,array($uid));
	    while($data->fetch_assoc()){
	        array_push($result, $data->getData('TryId'));
	    }
	    return $result;
	}
}